package com.mical.demo.respository;

import com.mical.demo.model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Repository
public class MessageRepository {

    private final JdbcTemplate template;

    private static final String CREATE_MESSAGE_SQL =
            "INSERT INTO message (message, ctime, user_id, type) VALUES (?, ?, ?, ?)";

    private static final String FIND_BY_USER_ID_SQL =
            "SELECT id, message, ctime, user_id, type FROM message WHERE user_id = ? ORDER BY ctime DESC";

    @Autowired
    public MessageRepository(JdbcTemplate template) {
        this.template = template;
    }

    public Message saveMessage(String content, int userId, int type) {
        Message message = new Message();
        message.setMessage(content);
        message.setCtime(new Date());
        message.setUserid(userId);
        message.setType(type);

        KeyHolder keyHolder = new GeneratedKeyHolder();

        template.update(connection -> {
            PreparedStatement ps = connection.prepareStatement(
                    CREATE_MESSAGE_SQL, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, content);
            ps.setTimestamp(2, new Timestamp(message.getCtime().getTime()));
            ps.setInt(3, userId);
            ps.setInt(4, type);
            return ps;
        }, keyHolder);

        message.setId(keyHolder.getKey().longValue());
        return message;
    }

    public List<Message> findByUserId(int userId) {
        return template.query(FIND_BY_USER_ID_SQL, new MessageRowMapper(), userId);
    }

    private static class MessageRowMapper implements RowMapper<Message> {
        @Override
        public Message mapRow(ResultSet rs, int rowNum) throws java.sql.SQLException {
            Message message = new Message();
            message.setId(rs.getLong("id"));
            message.setMessage(rs.getString("message"));
            message.setCtime(new Date(rs.getTimestamp("ctime").getTime()));
            message.setUserid(rs.getInt("userid"));
            message.setType(rs.getInt("type"));
            return message;
        }
    }
}